package com.glela.common.util;

import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author liujie
 */
public final class DateTimeUtil
{

	private static final int HOUR_MS = 3600 * 1000;

	public static final String DATESTYLEA_A = "yyyy-MM-dd";

	public static final String DATE_FORMAT_UTC	= "yyyy-MM-dd'T'HH:mm:ss'Z'";

	public static String format(Date date, String parttern)
	{
		if (null == date) {
			return "-";
		}
		if (parttern == null) {
			return date.toString();
		}
		SimpleDateFormat sdf = new SimpleDateFormat(parttern, new DateFormatSymbols());
		return sdf.format(date);
	}

	/**
	 * 得到两个日期相差的天数
	 */
	public static int getBetweenDay(Date date1, Date date2)
	{
		Calendar d1 = new GregorianCalendar();
		d1.setTime(date1);
		Calendar d2 = new GregorianCalendar();
		d2.setTime(date2);
		int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
		int y2 = d2.get(Calendar.YEAR);
		if (d1.get(Calendar.YEAR) != y2) {
			//			d1 = (Calendar) d1.clone();
			do {
				days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
				d1.add(Calendar.YEAR, 1);
			} while (d1.get(Calendar.YEAR) != y2);
		}
		return Math.abs(days);
	}

	public static Date getDNdayAgo(int n)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -n);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	public static int getHowManyHoursAgo(Date d)
	{
		return (int) (new Date().getTime() - d.getTime()) / HOUR_MS;
	}

	public static Date parseStrToDate(String dateStr)
	{
		return DateTimeUtil.parseStrToDate(dateStr, DATESTYLEA_A);
	}

	public static Date parseStrToDate(String dateStr, String format)
	{
		if (dateStr == null) {
			return null;
		}

		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format, new DateFormatSymbols());
			return sdf.parse(dateStr);
		}
		catch (Exception e) {
			return null;
		}
	}

	private DateTimeUtil()
	{
	}
}
